import React, { Component } from 'react';
import { observer, inject } from 'mobx-react';
import { withRouter,Route } from 'react-router-dom';
import { TabBar, Icon , Popover, ActionSheet, ActivityIndicator, Bubble, Result, Tools } from 'weaver-mobile';
import { ListAdvanced,TabPage,RouteLayout,Reply } from 'weaver-mobile-page';
import { toJS } from 'mobx';
import * as adapter from '../../constants/adapter';
import ChanceCard from '../card/Chance';
import CustomerCard from '../card/Customer';
import ContacterCard from '../card/Contacter';
import CustomerAddExist from '../form/CustomerAddExist';
import BusinessCard from '../form/BusinessCard';
import ChanceForm from '../form/ChanceForm';
import ContacterForm from '../form/ContacterForm';
import ContactListSingle from '../list/ContactListSingle';
// import ContactHomePage from '../list/ContactHomePage';

const Item = Popover.Item;
const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
  wrapProps = {
    onTouchStart: e => e.preventDefault(),
  };
}

const getLabel = Tools.getLabel;
const leftConfig = [
  { type: 'voice' },
  { type: 'blog-tupian' },  
  { type: 'tianjia' },
];

@inject('homeStore')
@withRouter
@observer
export default class Enter extends Component {
    constructor(props) {
      super(props);
      this.state = {
        span: [7, 1],
        curCustomerId:"",
        curChanceId:"",
        curContacterId:"",
        curTabPage:"",
      };
    }

    componentWillMount(){
      const {homeStore,match,params} = this.props;
      const ps = params ? params : match.params;
      homeStore.doNew(this, ps);
    }
  
    componentDidMount() {
      this.props.homeStore.doInit();
    }
  
    componentWillUnmount() {
      this.props.homeStore.doClear();
    }

    componentWillReceiveProps(nextProps) {
      const oldPath = this.props.location.pathname;
      const newPath = nextProps.location.pathname;
      if(oldPath.indexOf("Layout") != -1 || newPath.indexOf("Layout") != -1){
        return;
      }
      const oldType = this.props.match.params.type;
      const newType = nextProps.match.params.type;
      const oldListTabIndex = this.props.match.params.listTabIndex;
      const newListTabIndex = nextProps.match.params.listTabIndex;
      const store = this.props.homeStore;
      // if(newType === "crm_contact_home"){
      //   store.type = newType;
      //   return;
      // }
      if(oldType != newType){
        store.barTabChange(newType,newListTabIndex);
        return;
      }
      if(oldListTabIndex != newListTabIndex){
        store.topTabChange(newListTabIndex);
        return;
      }
      // 单击底部barItem刷新
      if(oldPath == newPath){
        store.reload(this.props.match.params);
        return;
      }
    }
  
    render() {
      let content = [];
      const store = this.props.homeStore;
      const {initResponsed,initSuccessed,initFailedMsg,type,listTabIndex,replyStore,tabBarHidden} = store;
      const { span, curCustomerId, curChanceId, curContacterId, curTabPage } = this.state;
      if(initResponsed){
          if(initSuccessed){
            const { listTab, listAd, showCheck, manager, isShowResource,leftTreeValueArray,cardLayout,contactLayout,createLayout,createLayoutScan } = store;                        
            let tabProps = {
              page:listTabIndex,
              swipeable:true,
              onChange: (tab) => {
                this.props.history.push("/main/"+type+"/"+tab.key);
              }
            };

            let btns = [];  
            let conditionUrl = "";         
            if(type == "crm_list" || type == "crm_partner"){
              conditionUrl = "/api/crm/mobile/getCustomerCondition?opt="+listTabIndex;
              btns.push(<i className='crm-list-header-icon icon-crm icon-crm-add' onClick={this.addCustomer.bind(this)}/>);
            }else if(type == "crm_chance"){
              conditionUrl = "/api/crm/mobile/getChanceCondition?opt="+listTabIndex;
              btns.push(<i className='crm-list-header-icon icon-crm icon-crm-add' onClick={this.addChance.bind(this)}/>);
            }else if(type == "crm_contacter"){
              conditionUrl = "/api/crm/mobile/getContacterCondition?opt="+listTabIndex;
              btns.push(<i className='crm-list-header-icon icon-crm icon-crm-add' onClick={this.addContacter.bind(this)}/>);
            }
            let tabPageProps = {};
            tabPageProps.btns = btns;
            tabPageProps.span = span;
            tabPageProps.tabs = listTab;
            tabPageProps.tabProps = tabProps;
            tabPageProps.popover = false;

            let listAdvancedProps = {};
            listAdvancedProps.store = listAd;
            listAdvancedProps.hasAdvanceSerach = true;
            listAdvancedProps.conditionFetchOptions = {url:conditionUrl,method:"GET"};
            listAdvancedProps.rowKey = "id";
            listAdvancedProps.searchKey = "searchKey";
            listAdvancedProps.showCheck = showCheck;
            listAdvancedProps.heightSpace = 50;
            // listAdvancedProps.customHeight = "100%";
            listAdvancedProps.onSearch = this.onSearch;
            listAdvancedProps.onRowClick = this.onRowClick.bind(this);
            let placeholder = "";
            if(type == "crm_list" || type == "crm_partner"){
              placeholder = getLabel("391028","名称或地址");
            }else{
              placeholder = "Search...";
            }
            if(type == "crm_list" || type == "crm_partner"){
              // console.log("manager",toJS(manager));
              listAdvancedProps.treeKey = "key";
              listAdvancedProps.showSearchBar = true;
              listAdvancedProps.onLeftTreeChange = this.onLeftTreeChange.bind(this);
              listAdvancedProps.leftTreeFetchOptions = {url: '/api/crm/mobile/getHrmTree',method: 'POST'};
              listAdvancedProps.searchBarProps = {
                showSelectButton: (listTabIndex==="my"&&isShowResource),
                selectText: manager.name?manager.name:manager.initname,
                placeholder: placeholder,
              };
              listAdvancedProps.leftTreeBrowserProps = {
                searchBarProps: {
                  placeholder: 'Search...',
                },
                valueArray: toJS(leftTreeValueArray)
              }
            }
            if(type == "crm_contacter"){
              listAdvancedProps.withSwipeAction = true;
              listAdvancedProps.swipeActionProps = {
                right: [
                  { 
                    text: <i className={'crm-nav-header-icon icon-crm icon-crm-phone'}/>,
                    onPress: (data) => { 
                      if(data.mobilephone.length == 11){
                        window.em.tel({'tel':data.mobilephone,'success':function (argument) {
                            // console.log('success');
                            // console.log(JSON.stringify(argument));
                          },'fail':function (argument) {
                            alert("window.em.tel fail:"+argument);
                            // console.log('fail')
                            // console.log(argument);
                          },'cancel':function (argument) {                        
                            // console.log('cancel')
                            // console.log(argument);
                          },'complete':function (argument) {
                            // console.log('complete')
                            // console.log(argument);
                        }});  
                      }else{
                        Bubble.warning(getLabel('390903',"请先维护手机号码"), 1, {backgroundColor:adapter.BUBBLE_BGCOLOR}, 2);
                      }
                    },
                    className: "crm-contacter-list-swipe",
                  },
                  { 
                    text: <i className={'crm-nav-header-icon icon-crm icon-crm-sms'}/>,
                    onPress: (data) => {  
                      if(data.mobilephone.length == 11){
                        window.em.textMessage({'mobile':data.mobilephone,'text':"",'success':function (argument) {
                            // console.log('success');
                            // console.log(JSON.stringify(argument));
                          },'fail':function (argument) {
                            alert("window.em.textMessage fail:"+argument);
                            // console.log('fail')
                            // console.log(argument);
                          },'cancel':function (argument) {                        
                            // console.log('cancel')
                            // console.log(argument);
                          },'complete':function (argument) {
                            // console.log('complete')
                            // console.log(argument);
                        }});
                      }else{
                        Bubble.warning(getLabel('390903',"请先维护手机号码"), 1, {backgroundColor:adapter.BUBBLE_BGCOLOR}, 2);
                      }
                    },
                    className: "crm-contacter-list-swipe",
                  },
                  { 
                    text: <i className={'crm-nav-header-icon icon-crm icon-crm-email'}/>,
                    onPress: (data) => {   
                      if(data.email.indexOf("@") != -1){
                        window.em.mailto({'mail':data.email,'success':function (argument) {
                            // console.log('success');
                            // console.log(JSON.stringify(argument));
                          },'fail':function (argument) {           
                            alert("window.em.mail fail:"+argument);             
                            // console.log('fail');
                            // console.log(argument);
                          },'cancel':function (argument) {
                            // console.log('cancel');
                            // console.log(argument);
                          },'complete':function (argument) {
                            // console.log('complete');
                            // console.log(argument);
                        }});    
                      }else{
                        Bubble.warning(getLabel('390905',"请先维护邮箱地址"), 1, {backgroundColor:adapter.BUBBLE_BGCOLOR}, 2);
                      }
                    },
                    className: "crm-contacter-list-swipe",
                  }
                ],
              };
            }
            if(type == "crm_list" || type == "crm_partner" || type == "crm_chance"){
              listAdvancedProps.withSwipeAction = true;
              listAdvancedProps.swipeActionProps = {
                right: [
                  { 
                    text: getLabel('390906',"查看联系"),
                    onPress: (data) => {
                      let customerId = "";
                      let chanceId = "";
                      if(type == "crm_list" || type == "crm_partner"){
                        customerId = data.id;
                        chanceId = "0";
                      }else{
                        customerId = data.customerid;
                        chanceId = data.id;
                      }
                      this.setState({curCustomerId:customerId,curChanceId:chanceId});
                      this.props.history.push(contactLayout.path);
                    },
                    className: "crm-list-swipe-yellow",
                  },
                  { 
                    text: getLabel('390937',"添加联系"),
                    onPress: (data) => {
                      let customerId = "";
                      let chanceId = "";
                      if(type == "crm_list" || type == "crm_partner"){
                        customerId = data.id;
                        chanceId = "0";
                      }else{
                        customerId = data.customerid;
                        chanceId = data.id;
                      }
                      this.setState({curCustomerId:customerId,curChanceId:chanceId});
                      store.resetReplyStore(customerId);
                      store.setBarHidden(true);
                      store.replyRef.setVisible(true, () => {
                        store.replyRef.getInputFocus();
                        // 设置相关商机的默认值      
                        if(chanceId > 0){        
                          store.replyStore.setState({attach:{chance:[{id: chanceId}]}});
                        }
                      });
                    },
                    className: "crm-list-swipe-green",
                  }                  
                ],
              };
            }

            content = <div>
              <TabPage {...tabPageProps}/>
              <div className="crm-list-content">
                <ListAdvanced {...listAdvancedProps}/>
              </div>
              <Route
                key={cardLayout.id}
                path={cardLayout.path}
                render={() => {
                  let detailContent;
                  let tabPage = curTabPage != "" ? curTabPage : "info";
                  if(type == "crm_list" || type == "crm_partner"){
                    detailContent = <CustomerCard params={{id:curCustomerId,tabPage:tabPage}}/>;
                  }else if(type == "crm_chance"){
                    detailContent = <ChanceCard params={{id:curChanceId,tabPage:tabPage}}/>;
                  }else if(type == "crm_contacter"){
                    detailContent = <ContacterCard params={{id:curContacterId}}/>;
                  }
                  return (
                    <RouteLayout getContainer={() => document.getElementById("root")}>
                      <div
                        key="cardLayout"
                        className="wm-route-layout"
                      >
                        {detailContent}
                      </div>
                    </RouteLayout>
                  )
                }}
              />
              <Route
                key={contactLayout.id}
                path={contactLayout.path}
                render={() => {              
                  return (
                    <RouteLayout getContainer={() => document.getElementById("root")}>
                      <div
                        key="contactLayout"
                        className="wm-route-layout"
                      >
                        <ContactListSingle params={{customerId:curCustomerId,chanceId:curChanceId}}/>
                      </div>
                    </RouteLayout>
                  )
                }}
              />
              <Route
                key={createLayout.id}
                path={createLayout.path}
                render={() => {
                  let detailContent;
                  if(type == "crm_list" || type == "crm_partner"){
                      // 新建客户
                      detailContent = <CustomerAddExist/>
                  }else if(type == "crm_chance"){
                      detailContent = <ChanceForm params={{operation:"add"}}/>;
                  }else if(type == "crm_contacter"){
                      // 新建联系人
                      detailContent = <ContacterForm params={{operation:"add"}}/>
                  }
                  return (
                    <RouteLayout getContainer={() => document.getElementById("root")}>
                      <div
                        key="createLayout"
                        className="wm-route-layout"
                      >                    
                        {detailContent}
                      </div>
                    </RouteLayout>
                  )
                }}
              />
              <Route
                key={createLayoutScan.id}
                path={createLayoutScan.path}
                render={() => {
                  let detailContent;
                  if(type == "crm_list" || type == "crm_partner"){
                      // 新建客户
                      detailContent = <BusinessCard/>
                  }else if(type == "crm_contacter"){
                      // 新建联系人
                      detailContent = <BusinessCard/>
                  }
                  return (
                    <RouteLayout getContainer={() => document.getElementById("root")}>
                      <div
                        key="createLayoutScan"
                        className="wm-route-layout"
                      >                    
                        {detailContent}
                      </div>
                    </RouteLayout>
                  )
                }}
              />
            </div>;
            // if(type == "crm_contact_home"){
            //   content = <div style={{height:"100%"}}><ContactHomePage params={{subType:"contact"}}/></div>              
            // }
          }else{
            content = <div>
                <Result
                  img={<Icon type="cross-circle-o" className="crm_commerce_initFailedMsg" style={{ fill: '#F13642' }} />}
                  title=""
                  message={initFailedMsg}
                />
            </div>;
          }
      }else{
        content = <div className="crm-bg-loading"><ActivityIndicator text="Loading..."/></div>;
      }

      return (
        <div className="crm_tabbar_reset" style={{height:"100%"}}>
            <TabBar
              hidden={tabBarHidden}
              unselectedTintColor='#949494' //未选中的字体颜色
              tintColor='#33A3F4' //选中的字体颜色
              barTintColor='white'
              tabBarPosition='bottom'
              prerenderingSiblingsNumber={0}
            >
              <TabBar.Item
                title={<span className={type=="crm_list" ? "crm-card-bar-title" : ""} style={{marginLeft:"-5px"}}>{getLabel('136','客户')}</span>}
                key='crm_list'
                icon={<i className='crm-nav-bar-icon icon-crm icon-crm-customer-o'/>}
                selectedIcon={<i className='crm-nav-bar-icon icon-crm icon-crm-customer'/>}
                selected={type === 'crm_list'} //是否选中
                onPress={() => {
                  this.props.history.push("/main/crm_list/my");
                }}              
              >
                {/* {content} */}
              </TabBar.Item>
              <TabBar.Item
                title={<span className={type=="crm_chance" ? "crm-card-bar-title" : ""} style={{marginLeft:"-3px"}}>{getLabel('32922','商机')}</span>}
                key='crm_chance'
                icon={<i className='crm-nav-bar-icon icon-crm icon-crm-sellchance-o'/>}
                selectedIcon={<i className='crm-nav-bar-icon icon-crm icon-crm-sellchance'/>}
                selected={type === 'crm_chance'} //是否选中
                onPress={() => {
                  this.props.history.push("/main/crm_chance/my");
                }}
              >
                {/* {content} */}
              </TabBar.Item>
              <TabBar.Item
                title={<span className={type=="crm_partner" ? "crm-card-bar-title" : ""} style={{marginLeft:"-3px"}}>{getLabel('388604','伙伴')}</span>}
                key='crm_partner'
                icon={<i className='crm-nav-bar-icon icon-crm icon-crm-partner-o'/>}
                selectedIcon={<i className='crm-nav-bar-icon icon-crm icon-crm-partner'/>}
                selected={type === 'crm_partner'} //是否选中
                onPress={() => {
                  this.props.history.push("/main/crm_partner/my");
                }}
              >
                {/* {content} */}
              </TabBar.Item>
              <TabBar.Item
                title={<span className={type=="crm_contacter" ? "crm-card-bar-title" : ""} style={{marginLeft:"-3px"}}>{getLabel('572','联系人')}</span>}
                key='crm_contacter'
                icon={<i className='crm-nav-bar-icon icon-crm icon-crm-contacter-o'/>}
                selectedIcon={<i className='crm-nav-bar-icon icon-crm icon-crm-contacter'/>}
                selected={type === 'crm_contacter'} //是否选中
                onPress={() => {
                  this.props.history.push("/main/crm_contacter/my");
                }}
              >
                {/* {content} */}
              </TabBar.Item>
              {/* <TabBar.Item
                title={<span className={type=="crm_contact_home" ? "crm-card-bar-title" : ""} style={{marginLeft:"-3px"}}>{getLabel('16405','联系情况')}</span>}
                key='crm_contact_home'
                icon={<i className='crm-nav-bar-icon icon-crm icon-crm-message-o'/>}
                selectedIcon={<i className='crm-nav-bar-icon icon-crm icon-crm-message'/>}
                selected={type === 'crm_contact_home'} //是否选中
                onPress={() => {
                  this.props.history.push("/main/crm_contact_home/my");
                }}
              > */}
                {/* {content} */}
              {/* </TabBar.Item> */}
            </TabBar>
            {content}
            <div className="crm_reply_mask">
              <Reply
                wrappedComponentRef={ref => {
                  if(ref){
                    store.replyRef = ref;
                  }
                }}
                placeholder={getLabel("84370","请填写联系记录")}
                store={replyStore}
                leftConfig={leftConfig}
                // showOutInput={showOutInput}
                onSubmit={datas => store.saveReply(datas,curCustomerId)}
                onMaskClick={()=>{
                  store.setBarHidden(false);
                  store.replyStore.doClear();
                }}
              >
              </Reply>
            </div>
        </div>
      );
    }

    onSearch = () => {
      this.props.homeStore.doSearch();
    }
  
    onRowClick(rowData){
      const store = this.props.homeStore;
      const {cardLayout,type} = store;
      if(type == "crm_list" || type == "crm_partner"){
        this.setState({curCustomerId:rowData.id});
      }else if(type == "crm_chance"){
        this.setState({curChanceId:rowData.id});
      }else if(type == "crm_contacter"){
        this.setState({curContacterId:rowData.id});
      }      
      this.props.history.push(cardLayout.path);
    }
  
    addCustomer(){
      const store = this.props.homeStore;
      const {isOpenCardScan,createLayout,createLayoutScan} = store;
      if(isOpenCardScan == 0){
        // 新建客户
        // this.props.history.push("/customerAddExist");
        this.props.history.push(createLayout.path); 
        return;
      }
      const BUTTONS = [
        {
          content: getLabel('388602','普通新建'),
          // onClick: () => console.log('Operation1'),
        },
        {
          content: getLabel('388603','名片识别'),
          // onClick: () => console.log('Operation2'),
        },
        {
          content: getLabel('201','取消'),
          // onClick: () => console.log('Operation3'),
        }
      ];
      ActionSheet.showActionSheetWithOptions({
        options: BUTTONS,
        cancelButtonIndex: 2,
        maskClosable: true,
        'data-seed': 'logId',
        wrapProps,
      },
      (buttonIndex) => {
        if(buttonIndex != BUTTONS.length - 1){
          if(buttonIndex == 0){
            this.props.history.push(createLayout.path);
          }else if(buttonIndex == 1){
            this.props.history.push(createLayoutScan.path);
          }
        }
      });
    }

    addChance(){
      const store = this.props.homeStore;
      const {createLayout} = store;
      this.props.history.push(createLayout.path);
    }

    addContacter(){
      const store = this.props.homeStore;
      const {isOpenCardScan,createLayout,createLayoutScan} = store;
      if(isOpenCardScan == 0){
        // 新建联系人
        //this.props.history.push("/contacterAdd/add");
        this.props.history.push(createLayout.path);
        return;
      }
      const BUTTONS = [
        {
          content: getLabel('388602','普通新建'),
          // onClick: () => console.log('Operation1'),
        },
        {
          content: getLabel('388603','名片识别'),
          // onClick: () => console.log('Operation2'),
        },
        {
          content: getLabel('201','取消'),
          // onClick: () => console.log('Operation3'),
        }
      ];
      ActionSheet.showActionSheetWithOptions({
        options: BUTTONS,
        cancelButtonIndex: 2,
        maskClosable: true,
        'data-seed': 'logId',
        wrapProps,
      },
      (buttonIndex) => {
        if(buttonIndex != BUTTONS.length - 1){
          if(buttonIndex == 0){
            this.props.history.push(createLayout.path);
          }else if(buttonIndex == 1){
            this.props.history.push(createLayoutScan.path);
          }
        }
      });
    }
  
    onLeftTreeChange(id,name,valuearray){
      const store = this.props.homeStore;
      store.onLeftTreeChange(id,name,valuearray);
    }
}